package com.example.shop_2212.fg

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.base.entity.Reply
import com.example.base.mvvm.BaseFragment
import com.example.shop_2212.R
import com.example.shop_2212.adapter.ChildAdapter
import com.example.shop_2212.adapter.GoodsAdapter
import com.example.shop_2212.adapter.OneAdapter
import com.example.shop_2212.databinding.FragmentCate2Binding
import com.example.shop_2212.fgviewmodel.CategoryViewModel

class Cate2Fragment : BaseFragment<FragmentCate2Binding,CategoryViewModel>() {
    lateinit var oneAdapter: OneAdapter//一级
    lateinit var childAdapter: ChildAdapter//二级
    lateinit var goodsAdapter: GoodsAdapter//三级

    override fun getLayout(): Int = R.layout.fragment_cate2

    override fun getViewModel(): Class<CategoryViewModel>  = CategoryViewModel::class.java

    override fun initView() {
        oneAdapter = OneAdapter()
        binding.rvOne.adapter = oneAdapter
        binding.rvOne.layoutManager = LinearLayoutManager(context)

        childAdapter = ChildAdapter()
        binding.rvTwo.adapter = childAdapter
        binding.rvTwo.layoutManager = GridLayoutManager(context,3)

        goodsAdapter = GoodsAdapter()
        binding.rvThree.adapter = goodsAdapter
        binding.rvThree.layoutManager = LinearLayoutManager(context)

        viewModel.category()//请求一级二级分类数据

        //点击一级分类  二级数据变化 三级数据变化
        oneAdapter.setOnItemClickListener { adapter, view, position ->
            //加载二级
            childAdapter.data.clear()
            childAdapter.data.addAll(oneAdapter.data[position].child)
            childAdapter.notifyDataSetChanged()
            //加载三级
            viewModel.cateDetail(childAdapter.data[0].id,"",10,true,1,"","")
        }
        //点击二级   三级数据发生变化
        childAdapter.setOnItemClickListener { adapter, view, position ->
            //加载三级
            viewModel.cateDetail(childAdapter.data[position].id,"",10,true,1,"","")
        }


    }

    override fun initData() {
        viewModel.categorySuccess.observe(this){
            if(it.code==200){
                //加载一级
                oneAdapter.data.clear()
                oneAdapter.data.addAll(it.data)
                oneAdapter.notifyDataSetChanged()
                //加载二级
                childAdapter.data.clear()
                childAdapter.data.addAll(it.data[0].child)
                childAdapter.notifyDataSetChanged()
                //加载三级
                viewModel.cateDetail(childAdapter.data[0].id,"",10,true,1,"","")
            }
        }
        viewModel.success.observe(this){
            goodsAdapter.data.clear()
            goodsAdapter.data.addAll(it.data.list)
            goodsAdapter.notifyDataSetChanged()
        }
    }

}